const express = require('express');
const router = express.Router();
const userModel = require('../../models/userModel')
const md5 = require('md5')




//注册页面
router.get('/reg', (req, res) => {
  res.render('login/reg')
})
//用户注册
router.post('/reg', (req, res) => {
  console.log(req.body)
  userModel.create({...req.body,password:md5(req.body.password)})
    .then((data) => {
   res.render('success',{msg:'注册成功',url:'/login'})
  })
    .catch((err) => {
      res.send('注册失败')
    })

  // res.render('login/reg')
})


//用户登录
router.get('/login', (req, res) => {
  res.render('login/login')
})
router.post('/login', (req, res) => {
  const {username,password} = req.body
  //查询数据库
  userModel.findOne({username:username,password:md5(password)}).then((data) => {
    if (!data){
      res.send('账号或者密码错误')
    }
    else {
     req.session.username = username
     req.session._id = data._id
    res.render('success',{msg:'登录成功',url:'/account'})
    }
  })

})


//用户退出
router.post('/logout',(req, res) => {
  req.session.destroy(() => {
    res.render('success', {msg:'退出成功', url:'/login'})
  })
})

module.exports = router;
